import { defineStore } from 'pinia';
import { login,logout } from '@/api/user';
import { ElMessage, ElLoading } from 'element-plus';
import { setToken } from '@/utils/token';

export const useUserStore = defineStore('user', {
	state() {
		return {
			userInfo: {}, // 用户信息
			token: '', // token
			menus: [],
		};
	},
	actions: {
		// 退出登录 并跳转到登录页面
		async logout(router) {
			localStorage.clear();
			this.$reset();
			await logout()
			router.push({ name: 'login' });
		},
		async login(data, router) {
			const res = await login(data);
			if (res.code == 0) {
				this.userInfo = res.data;
				this.token = res.data.token;
				setToken(this.token);
				ElMessage.success('登录成功');
				router.push({ path: '/' });
			} else {
				ElMessage.error(res.msg);
			}
		},
		setMenuList(menus) {
			this.menus = menus;
		},
	},
	persist: true,
});
